package service

import (
	"ApplicationRunCrontab/app/dao"
	"ApplicationRunCrontab/app/model"
	"ApplicationRunCrontab/library/utils"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
	"strconv"
)

type dyVideoService struct{}

var DyVideo = &dyVideoService{}

func (s *dyVideoService) DYSync() {
	var ops []*model.JdyRunDirectOpen
	err := dao.JdyRunDirectOpen.Where(dao.JdyRunDirectOpen.C.NextTime+" < ", utils.TimeMillisecond()).Where(dao.JdyRunDirectOpen.C.Status, 1).Limit(100).Scan(&ops)
	if err != nil || len(ops) == 0 {
		g.Log().Info("未找到需要同步的账号信息")
		return
	}
	for _, v := range ops {
		if v.DySecUid == "" {
			continue
		}
		//查询信息
		result, code := utils.TKKeywordAwemeUser(v.DySecUid, 10, 0)
		if code != 200 {
			g.Log().Info("doutk抖音号详情请求失败")
			continue
		}
		j, jErr := gjson.DecodeToJson(result)
		if jErr != nil {
			g.Log().Info("doutk抖音号详情解析失败")
			continue
		}
		rCode := j.GetInt("code")
		if rCode != 0 {
			g.Log().Info("doutk抖音号详情返回数据失败")
			continue
		}
		data := j.GetJson("data")
		if data != nil {
			var video model.JdyRunDirectDouyinVideo
			var videos []model.JdyRunDirectDouyinVideo
			awemeList := j.GetStrings("data.aweme_list")
			for _, vv := range awemeList {
				video.DirectAccountId = v.DirectAccountId
				video.OpenId = v.Id
				video.DyNickname = v.DyNickname
				video.DyAccountName = v.DyAccountName
				video.DyAvatar = v.DyAvatar
				b, _ := gjson.DecodeToJson(vv)
				video.Title = b.GetString("desc")
				videos = append(videos, video)
			}
			//存储当日账户数据情况
			_, err1 := dao.JdyRunDirectDouyinInfo.Data(videos).Insert()
			if err1 != nil {
				g.Log().Info(">>>> 用户抖音账号信息插入数据库表失败 <<<<")
			}
			//修改记录下次执行时间，默认一日统计一次
			nTime := utils.TimeMillisecond() + 86400000
			_, uErr := dao.JdyRunDirectOpen.Data(g.Map{dao.JdyRunDirectOpen.C.NextTime: nTime}).Where(g.Map{dao.JdyRunDirectOpen.C.Id: v.Id}).Update()
			if uErr != nil {
				g.Log().Info("doutk抖音号详情修改失败" + strconv.FormatUint(v.DirectAccountId, 10) + uErr.Error())
				continue
			}
		}
	}
	//递归同步账号
	if len(ops) == 100 {
		s.DYSync()
	}
}

// 获取抖音账号的视频
func getVideoByUser(uid string, cursor int, videosCh chan<- model.JdyRunDirectDouyinVideo) {
	result, code := utils.TKKeywordAwemeUser(uid, 10, cursor)
	if code != 200 {
		g.Log().Info("doutk抖音号详情请求失败")
		continue
	}
	j, jErr := gjson.DecodeToJson(result)
	if jErr != nil {
		g.Log().Info("doutk抖音号详情解析失败")
		continue
	}
	rCode := j.GetInt("code")
	if rCode != 0 {
		g.Log().Info("doutk抖音号详情返回数据失败")
		continue
	}
	data := j.GetJson("data")
	if data == nil {
		return
	}

	awemeList := j.GetStrings("data.aweme_list")
	for _, vv := range awemeList {
		var video model.JdyRunDirectDouyinVideo
		video.DirectAccountId = v.DirectAccountId
		video.OpenId = v.Id
		video.DyNickname = v.DyNickname
		video.DyAccountName = v.DyAccountName
		video.DyAvatar = v.DyAvatar
		b, _ := gjson.DecodeToJson(vv)
		video.Title = b.GetString("desc")

		videosCh <- video
	}

	hasMore := j.GetBool("data.has_more")
	cursor = j.GetInt("data.max_cursor")
	if !hasMore || cursor <= 0 {
		return
	}

	getVideoByUser(uid, cursor, videosCh)

}

func (s *dyVideoService) DYSync1() {
	videosCh := make(chan model.JdyRunDirectDouyinVideo, 1000)
	var ops []*model.JdyRunDirectOpen
	err := dao.JdyRunDirectOpen.Where(dao.JdyRunDirectOpen.C.NextTime+" < ", utils.TimeMillisecond()).Where(dao.JdyRunDirectOpen.C.Status, 1).Limit(100).Scan(&ops)
	if err != nil || len(ops) == 0 {
		g.Log().Info("未找到需要同步的账号信息")
		return
	}

	// 获取视频
	go func() {
		defer close(videosCh) // 获取视频结束，关闭chan
		for _, v := range ops {
			if v.DySecUid == "" {
				continue
			}
			getVideoByUser(v.DySecUid, 0, videosCh)
		}
	}()

	// 保存视频
	var insertSize = 500
	var videos = make([]model.JdyRunDirectDouyinVideo, 0, insertSize)
	for ch := range videosCh {
		videos = append(videos, ch)
		if len(videos) < insertSize {
			continue
		}

		_, err1 := dao.JdyRunDirectDouyinInfo.Data(videos).Insert()
		if err1 != nil {
			g.Log().Info(">>>> 用户抖音账号信息插入数据库表失败 <<<<")
		}

	}

	//修改记录下次执行时间，默认一日统计一次
	nTime := utils.TimeMillisecond() + 86400000
	_, uErr := dao.JdyRunDirectOpen.Data(g.Map{dao.JdyRunDirectOpen.C.NextTime: nTime}).Where(g.Map{dao.JdyRunDirectOpen.C.Id: v.Id}).Update()
	if uErr != nil {
		g.Log().Info("doutk抖音号详情修改失败" + strconv.FormatUint(v.DirectAccountId, 10) + uErr.Error())
		continue
	}

}


func (){

	_ = dao.JdyRunDirectDouyinVideo.Group(dao.JdyRunDirectDouyinVideo.C.OpenId).Fields("open_id,max(aweme_id) as aweme_id").Scan(&fs)
	tmpMap:=make(map[string]string)
	for _, v := range ps {
		_, ok := videos[v.AwemeId]
		if ok {
			delete(videos, v.AwemeId)
		}
	}

	for _, v := range fs {
		tmpMap[v.OpenId]=v.AwemeId
	}

	openids:=[]string{}
	for _, vv := range videos {
		if vv.AwemeId<tmpMap[vv.OpenId]{
			continue
		}
		ks = append(ks, vv)
	}



}